<?php
/**
 * 媒资管理上传
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 10:02
 */

namespace app\api\controller\homepage;

use app\api\controller\common\ApiBase;
use app\api\model\BaseCategory;
use app\api\model\MediaFiles;
use app\api\service\Uploader;
use think\Controller;
use think\Db;
use think\Loader;
use think\Log;

class Upload extends ApiBase
{

    protected $model = null;
    protected $media_model = null;

    public function _initialize()
    {
        $this->model = new MediaFiles();
        $this->media_model = new \app\api\model\Media();
        $this->admin = session('admin');
    }

    public function list()
    {
        $data = $this->request->param();

        $list = $this->media_model->getList();

        $this->success('获取成功', '', $list);
    }


    /**
     * 创建
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 22:03
     */
    public function add()
    {

        $this->model = new \app\api\model\Media();
        $post = $this->request->param();

        $validate = Loader::validate('Media');

        $res = $validate->scene('add')->check($post);
        if (!$res) {
            $this->error($validate->getError());
        }
        
        $cateids = $post['cate_ids'] ? explode(',', $post['cate_ids']) : [];
        unset($post['cate_ids']);

        $post['admin_id'] = $this->admin['id'];

        $this->model->startTrans();

        $result = $this->model->save($post);
        if ($result === false) {
            $this->model->rollback();
            $this->error('创建失败');
        }

        // 分类
        $cateids_list = (new BaseCategory())->getIdByList($cateids);

        $cate_result = $this->model->category()->saveAll($cateids_list);
        if ($cate_result === false) {
            $this->model->rollback();
            $this->error('创建失败');
        }

        $this->model->commit();
        $this->success('创建成功', '', ['media_id' => $this->model->id]);
    }
//
//    public function edit()
//    {
//
//        $post = $this->request->param();
//
//        $validate = Loader::validate('Media');
//
//        $res = $validate->scene('edit')->check($post);
//        if (!$res) {
//            $this->error($validate->getError());
//        }
//
//        $media_id = $post['media_id'];
//        $cateids = $post['cate_ids'] ? explode(',', $post['cate_ids']) : [];
//        unset($post['cate_ids']);
//        unset($post['media_id']);
//        $detail = $this->model->get($media_id);
//        if (empty($detail)) {
//            $this->error('资源不存在');
//        }
//
//        $this->model->startTrans();
//
//        $result = $detail->save($post);
//        if ($result === false) {
//            $this->model->rollback();
//            $this->error('编辑失败');
//        }
//
//        // 分类
//        $cateids_list = (new BaseCategory())->getIdByList($cateids);
//        $detail->category()->delete();
//        if ($cateids_list) {
//            $cate_result = $detail->category()->saveAll($cateids_list);
//            if ($cate_result === false) {
//                $this->model->rollback();
//                $this->error('编辑失败');
//            }
//        }
//
//
//        $this->model->commit();
//        $this->success('编辑成功');
//    }


    public function edit()
    {

        $post = $this->request->param();

        $validate = Loader::validate('Media');

        $res = $validate->scene('edit')->check($post);
        if (!$res) {
            $this->error($validate->getError());
        }

        $media_id = $post['media_id'];
        $cateids = $post['cate_ids'] ? explode(',', $post['cate_ids']) : [];
        unset($post['cate_ids']);
        unset($post['media_id']);
        $detail = $this->media_model->get($media_id);
        if (empty($detail)) {
            $this->error('资源不存在');
        }

        $this->media_model->startTrans();

        $result = $detail->save($post);
        if ($result === false) {
            $this->media_model->rollback();
            $this->error('编辑失败');
        }

        // 分类
        $cateids_list = (new BaseCategory())->getIdByList($cateids);
        $detail->category()->delete();
        if ($cateids_list) {
            $cate_result = $detail->category()->saveAll($cateids_list);
            if ($cate_result === false) {
                $this->media_model->rollback();
                $this->error('编辑失败');
            }
        }

        $this->model->commit();
        $this->success('编辑成功');
    }


    public function detail()
    {

        $media_id = $this->request->param('media_id', 0);

        $detail = $this->media_model->getMediaData($media_id);

        if (empty($detail)) {
            $this->error('资源不存在');
        }

        $file_list = (new MediaFiles())->getList($media_id, 1);

        $this->success('获取成功', '', [
            'detail'    => $detail,
            'file_list' => $file_list
        ]);

    }

    /**
     * 删除|批量删除
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 23:13
     */
    public function del()
    {
        $ids = $this->request->post('ids', '');

        if (empty($ids))  {
            $this->error('参数缺少或为空');
        }
        $ids = $ids ?
            explode(',', $ids) : [];
        $map = [];
        $map['id'] = [
            'in',
            $ids
        ];
        $result = $this->media_model->where($map)
            ->update(['is_deleted' => '1']);

        if ($result === false) {
            $this->error('删除失败');
        }

        $this->model->where(['media_id' => ['in', $ids]])->update(['is_deleted' => '1']);
        $this->model->del_dev_file($ids);
        foreach ($ids as $item) {
            // 更新类目下载数量
            $this->media_model->updateDownloadNum($item);
        }
        $this->success('删除成功');
    }


    /**
     * 删除|批量删除
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 23:13
     */
    public function media_file_del()
    {
        $ids = $this->request->post('ids', '');

        $ids = $ids ?
            explode(',', $ids) : [];
        $map = [];
        $map['id'] = [
            'in',
            $ids
        ];
        $result = $this->model->where($map)
            ->update(['is_deleted' => '1']);

        if ($result === false) {
            $this->error('删除失败');
        }


        $this->model->del_dev_file("", $ids);
        $media_list = $this->model->where($map)->select();
        foreach ($media_list as $item) {
            // 更新类目下载数量
            $this->media_model->updateDownloadNum($item['media_id']);
        }
        $this->success('删除成功');
    }

    /**
     * 素材上传列表
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-15 20:08
     */
    public function upload_list()
    {
        $list = $this->model->getUploadList();
        $this->success('获取成功', '', $list);
    }

    /**
     * 素材压缩列表
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-15 20:08
     */
    public function compress_list()
    {
        $list = $this->model->getCompressList();
        $this->success('获取成功', '', $list);
    }

    public function upload()
    {
        $post = $this->request->param();
        $validate = Loader::validate('Upload');

        $res = $validate->scene('upload')->check($post);
        if (!$res) {
            $this->error($validate->getError());
        }

        // 参数校验
        $up = new Uploader();
        $media = $this->media_model->get($post['media_id']);
        if (empty($media)) {
            $this->error('媒咨不存在');
        }

        // 新增文件
        $media_file = $this->model->get([
            'is_deleted' => '0',
            'media_id'   => $media['id'],
            'identifier' => $post['identifier'],
            'file_size'  => $post['totalSize']
        ]);


        // 处理记录
        $media_file_id = $post['media_file_id'] ?? 0;

        $sort = $this->media_model->getMediaFileSort($media['id']);
        $progrss = intval(100 / $post['totalChunks']);

        // 已完成
        if ($media_file && $media_file['status'] == '1') {
            $data = $media_file->toArray();
            unset($data['id']);
            unset($data['create_time']);
            unset($data['update_time']);
            $data['title'] = $media['title'] . ($sort < 10 ? '0' . $sort : $sort);
            $data['sort'] = $sort;
            $result = $this->model->allowField(true)->save($data);
            if ($result === false) {
                $this->error('上传失败');
            }
            $this->success('上传成功');
        }
        // 新增插入进度
        $data = [
            'media_id'   => $media['id'],
            'title'      => $media['title'] . ($sort < 10 ? '0' . $sort : $sort),
            'type'       => $media['type'],
            'file_name'  => $post['filename'],
            'file_type'  => (new Uploader())->getFileExt($post['filename']),
            'file_size'  => $post['totalSize'],
            'sort'       => $sort,
            'identifier' => $post['identifier'],
            'image_json' => json_encode($post),
        ];
        if ($media_file_id > 0) {
            $media_file = $this->model->get($media_file_id);
            // 重置文件参数
            if ($media_file['status'] == '2') {
                $data['status'] = '0';
                $data['upload_progress'] = 0;
                $data['file_path'] = '';
                unset($sort);
                $media_file->save($data);
            }
        } else {
            if (!$media_file) {
                $media_file = $this->model;
                $media_file->save($data);
            }
        }

        // 记录文件ID
        $up->fileInfo = [
            'identifier'  => htmlentities($_POST['identifier']),
            //每个文件的唯一标识
            'filename'    => htmlentities($_POST['filename']),
            //文件名称
            'totalSize'   => intval($_POST['totalSize']),
            //文件总大小
            'chunkNumber' => intval($_POST['chunkNumber']),
            //当前是第几个分片
            'totalChunks' => intval($_POST['totalChunks'])
            //总分片数
        ];

        $res = $up->upload();

        if ($res['code']) {
            // 更新进度
            $this->model->where('id', $media_file['id'])->setInc('upload_progress', $progrss);

            // 上传已完成
            if (!$res['merge']) {
                $media_file->save([
                    'status'          => '1',
                    'upload_progress' => 100,
                    'file_path'       => $res['update']['file_path']
                ]);
            }
        }


        return json($res);
    }

    // 合并
    public function merge()
    {
        // 参数校验
        $post = $this->request->post();
        $validate = Loader::validate('Upload');
        $res = $validate->scene('merge')->check($post);
        if (!$res) {
            $this->error($validate->getError());
        }
        $up = new Uploader();
        $media = $this->media_model->get($post['media_id']);
        if (empty($media)) {
            $this->error('媒咨不存在');
        }
        $media_file = $this->model->get([
            'media_id'   => $post['media_id'],
            'identifier' => $post['identifier']
        ]);

        if ($media_file['status'] == '1') {
            $this->success('合并成功');
        }
        $up = new Uploader();
        $up->fileInfo = [
            'filename'    => htmlentities($post['filename']),
            //文件名称
            'identifier'  => htmlentities($post['identifier']),
            //文件唯一标识
            'totalSize'   => intval($post['totalSize']),
            //文件总大小
            'totalChunks' => intval($post['totalChunks'])
            //总分片数
        ];
        $res = $up->merge();

        if ($res['code']) {

            if ($media_file) {
                $media_file->save([
                    'status'          => 1,
                    'upload_progress' => 100,
                    'file_path'       => $res['update']['file_path']
                ]);
            }
        }
        return json($res);
    }


    /**
     * 重新转码
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-16 22:42
     */
    public function re_compress()
    {
        $id = $this->request->post('id', '');

        if (empty($id)) {
            $this->error('参数异常');
        }
        $map = [];
        $map['id'] = $id;
        $file = $this->model->get([
            'id'         => $id,
            'is_deleted' => '0'
        ]);
        if (empty($file)) {
            $this->error('素材不存在');
        }
        if ($file['compress_progress'] != 2) {
            $this->error('素材状态异常,请检查是否已在处理中');
        }
        $result = $this->model->where($map)
            ->update([
                'compress_status'   => 0,
                'compress_progress' => 0
            ]);

        if ($result === false) {
            $this->error('操作成功');
        }

        $this->success('操作失败');

    }


    // getSeachertypes
    public function getSeachertypes()
    {
        $parent = db('jq_base_cate')->where([
            'is_delete' => 0,
            'status'    => 1,
            'parent_id' => 0
        ])->order('sort desc')->select();
        $list = db('jq_base_cate')->where([
            'is_delete' => 0,
            'status'    => 1,
            'parent_id' => array(
                'gt',
                0
            )
        ])->select();
        foreach ($parent as &$v) {
            $v['children'] = [];
            foreach ($list as &$vv) {
                if ($vv['parent_id'] == $v['id']) {
                    $v['children'][] = $vv;
                }
            }
        }


        return json([
            'code' => 1,
            'msg'  => 'success',
            'data' => $parent
        ]);

    }

}